package com.maikang.exammall.entity.dto.order;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.maikang.exammall.entity.Order;
import com.maikang.exammall.entity.OrderItem;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrderDetailDTO {
    @ApiModelProperty("订单扼要")
    private OrderBrief orderBrief;

    @ApiModelProperty("套餐扼要")
    private List<GroupedOrderItems> groupedOrderItems;


    public static List<OrderDetailDTO> ofOrderList(List<Order> orders) {
        List<OrderDetailDTO> orderDetailDTOS = new ArrayList<>();
        if (ObjectUtils.isEmpty(orders)) return orderDetailDTOS;
        orders.forEach(order -> orderDetailDTOS.add(new OrderDetailDTO(order)));
        return orderDetailDTOS;
    }

    public OrderDetailDTO(Order order) {
        if (order == null) return;
        List<OrderItem> orderItems = order.getOrderItems();
        Map<Long, GroupedOrderItems> pkgIdPkgMap = new HashMap<>();
        orderItems.forEach(orderItem -> {
            Long pkgId = orderItem.getPkgId();
            pkgIdPkgMap.putIfAbsent(pkgId, new GroupedOrderItems(orderItem));
            GroupedOrderItems pkgBrief = pkgIdPkgMap.get(pkgId);
            pkgBrief.setPkgCount(pkgBrief.getPkgCount() + 1);
            pkgBrief.getOrderItems().add(orderItem);
        });

        this.groupedOrderItems = new ArrayList<>(pkgIdPkgMap.values());
        this.orderBrief = new OrderBrief(order);
    }

}

